package main.social.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;

import main.social.dao.UserDao;
import main.social.entities.Accounts;
import main.social.entities.Users;

public class UserDaoImpl extends AbstractGenericDao<Users, Long> implements
		UserDao {

	@SuppressWarnings("rawtypes")
	@Override
	public Users getByUsername(final String username) {
		Users user = null;
		try {
			List list = getHibernateTemplate().executeFind(
					new HibernateCallback() {

						@Override
						public List doInHibernate(Session session)
								throws HibernateException, SQLException {
							List list = null;
							try {
								DetachedCriteria account  = DetachedCriteria.forClass(Accounts.class);
								account.setProjection(Projections.property("id"));
								account.add(Restrictions.eq("username", username));
								list = session
										.createCriteria(getPersistentClass())
										.add(Subqueries.propertyEq("account", account)).list();
							} catch (HibernateException he) {
								return null;
							}
							return list;
						}
					});
			if ((list != null) && (list.size() > 0)) {
				user = (Users) list.get(0);
			}
		} catch (DataAccessException dae) {
			return null;
		}
		return user;
	}

}
